class Solution {
public:
    int dx[4] = { 0,0,1,-1 };
    int dy[4] = { 1,-1,0,0 };
    int getMaximumGold(vector<vector<int>>& grid)
    {
        int n = grid.size(), m = grid[0].size();
        vector<vector<bool>> check(n, vector<bool>(m, false));
        int ans = INT_MIN;

        function<int(int, int, int)> dfs = [&](int i, int j, int sum) {
            ans = max(ans, sum);
            for (int a = 0; a < 4; a++)
            {
                int x = dx[a] + i, y = dy[a] + j;
                if (x >= 0 && x < n && y >= 0 && y < m && !check[x][y] && grid[x][y])
                {
                    check[x][y] = true;
                    dfs(x, y, sum + grid[x][y]);
                    check[x][y] = false;
                }
            }
            return ans;
            };

        for (int i = 0; i < n; i++)
        {
            for (int j = 0; j < m; j++)
            {
                if (grid[i][j])
                {
                    check[i][j] = true;
                    dfs(i, j, grid[i][j]);
                    check[i][j] = false;
                }
            }
        }
        return ans == INT_MIN ? 0 : ans;
    }
};